<template>
  <a-upload
      name="avatar"
      listType="picture-card"
      class="avatar-uploader"
      :show-Upload-List="false"
      :customRequest="customRequest"
      :beforeUpload="beforeUpload"
      @change="handleChange"

  >
    <img v-if="imageUrl" :src="imageUrl" alt="avatar" class="img"/>
    <div v-else>
      <a-icon :type="loading ? 'loading' : 'plus'"/>
      <div class="ant-upload-text">上传图片</div>
    </div>
  </a-upload>
</template>

<script>

import {put} from '@/utils/OSS'
import store from "@/store";
import {ref} from "vue";

export default {
  name: 'SUpload',
  data() {
    return {
      loading: false,
      imageUrl: ref(store.getters.getImageUrl)
    }
  },
  props: {
    initData: {
      type: Object,
      required: true
    },
    formItemLayout: {
      type: Object,
      default: () => {
        return {
          Col: {
            md: 12
          },
          labelCol: {
            md: 24
          },
          wrapperCol: {
            md: 24
          }
        }
      }
    }
  },
  methods: {
    customRequest(action) {
      const file = action.file
      put(new Date().valueOf() + parseInt(Math.random() * 10000) + file.name.substring(0, 20), file).then(result => {
        this.loading = false
        this.imageUrl = result.url
        console.log(this.imageUrl)
        store.commit("setImageUrl", this.imageUrl)
      }).catch(e => {
        // this.log('异常')
        put(new Date().valueOf() + parseInt(Math.random() * 10000) + file.name.substring(0, 20), file).then(result => {
          this.loading = false
          this.imageUrl = result.url
          store.commit("setImageUrl", this.imageUrl)
        })
      })
    },
    handleChange(info) {
      if (info.file.status === 'uploading') {
        this.loading = true
      }
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('只允许上传图片')
      }
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$message.error('图片最大10MB!')
      }
      if (isJpgOrPng && isLt10M) {
      }
      return isJpgOrPng && isLt10M
    }
  }
}
</script>


<style>
.img {
  width: 400px;
  height: 400px;
  /*border: black 1px solid;*/
  background-color: darkgrey;
  object-fit: cover;
  object-position: 50% 20%;
}



</style>